//
//  PCPhotoMatchColumnVC.m
//  PhotoCircle
//
//  Created by wujungao on 12/15/15.
//  Copyright © 2015 wujungao. All rights reserved.
//

#import "PCPhotoMatchColumnVC.h"
#import "photoExhibitionHeadView.h"
#import "leftCell.h"
#import "rightCell.h"
#import "PCShowPhotoCommVC.h"
#import "SVPullToRefresh.h"
#import "UIImage+Convenience.h"
#import "NSDate+Convenience.h"
#import "fetchData.h"
#import "GMString.h"
#import "searchBar.h"
#import "gameListModel.h"
#import "nodataCell.h"
#import "PCUserModel.h"

#define topViewAndStatusBarH ([UIApplication sharedApplication].statusBarFrame.size.height+self.topView.frame.size.height)
#define cancelBtnW 49

//the imageW is base value:cellW/H and imageH come from imageW.
#define cellW  (SCREEN_W/2.0)
#define cellH  (0.5+5+imageH+5+55+5)
#define imageW ((SCREEN_W/2.0) - 15)
#define imageH ((imageW * 9) / 16)

typedef NSString sortType;

static NSString *leftCellID=@"leftCell";
static NSString *rightCellID=@"rightCell";
static NSString *headID=@"matchhead";
static NSString *nodataCellID=@"nodataCell";

@interface PCPhotoMatchColumnVC ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UISearchBarDelegate>

@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIButton *backBtn;
@property (weak, nonatomic) IBOutlet UIButton *searchBtn;
@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentCtrl;

- (IBAction)segmentCtrlAction:(UISegmentedControl *)sender;
- (IBAction)backBtnAction:(UIButton *)sender;
- (IBAction)searchBtnAction:(UIButton *)sender;

@property(nonatomic,strong)UIView *redLineView;
@property (strong,nonatomic) UICollectionView *photoMatchColumnView;
@property (assign,nonatomic) CGRect photoMatchColumnViewRect;

@property(nonatomic,strong)NSMutableArray *gameListModelArray;

@property(assign,nonatomic)NSInteger pageNum;
@property(nonatomic,strong)NSString *UUID;
@property(nonatomic,strong)sortType *sorType;
@property(nonatomic,strong)NSString *token;

@property(nonatomic,strong)searchBar *searchBar;
@property(nonatomic,strong)NSMutableArray *searchMatchArray;
@property(assign,nonatomic)NSInteger searchPageNum;
@property(nonatomic,assign)BOOL searchingFlag;
@property(nonatomic,strong)NSString *searchKeyText;

@property(nonatomic,strong)UIView *searchAlphaView;
@property(nonatomic,strong)UIButton *cancelBtn;
@property(nonatomic,assign)BOOL nodataFlag;

@end

@implementation PCPhotoMatchColumnVC

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [self configNavAndTabBar];
    self.photoMatchColumnView.alwaysBounceVertical=YES;
    [self.photoMatchColumnView.infiniteScrollingView stopAnimating];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //views
    [self configBtn];
    [self configRefresh];
    [self configPhotoExhibitionView];
    //data
    [GMTipsHelper showLoading];
    [self toRefresh];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - receive parameter
-(void)passUUID:(NSString *)uuid{
    
    self.UUID=uuid;
}

#pragma mark - config view method
-(void)configBtn{
    
    self.searchBtn.imageView.contentMode=UIViewContentModeScaleAspectFit;
}

-(void)configRefresh{
    
    __weak typeof(self) weakSelf=self;
    
    [self.photoMatchColumnView addPullToRefreshWithActionHandler:^{
        
        if(weakSelf.searchingFlag){
            
            [weakSelf searchPhotoMatch];
            
        }else{
            
            [weakSelf toRefresh];
        }
    }];
    
    [self.photoMatchColumnView addPullToRefreshWithTriggerHandler:^{
        [weakSelf toTrigger];
    }];
    
    [self.photoMatchColumnView addInfiniteScrollingWithActionHandler:^{
        
        if(weakSelf.searchingFlag){
            
            [weakSelf searchPhotoMatchLoadMore];
            
        }else{
            
            [weakSelf toLoadMore];
        }
    }];
}

-(void)configNavAndTabBar{
    
    if(self.searchingFlag){
        
        MCHiddenNavBar();
        MCHiddenNavBackButton();
        MCHiddenTabBar();
        MCHiddenBottomView();
        
    }else{
    
        MCShowNavBar();
        MCShowNavBackButton();
        MCHiddenTabBar();
        MCHiddenBottomView();
    }
    
    [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
    self.navigationController.navigationBar.translucent = NO;
    [self.view addSubview:self.redLineView];
}

-(void)configPhotoExhibitionView{
    
    self.photoMatchColumnView.delegate=self;
    self.photoMatchColumnView.dataSource=self;
    self.photoMatchColumnView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:self.photoMatchColumnView];
}

#pragma mark - fetch data method
-(void)toRefresh{
    
    NSDictionary *dictMid=[self parameterObj];
    self.pageNum=1;
    
    NSDictionary *dict=@{@"uuid":dictMid[@"uuid"],@"sort_type":dictMid[@"sort_type"],@"search_key":dictMid[@"search_key"],@"page":@1,@"token":dictMid[@"token"]};
    
    [[fetchData shared] fetchMatchListWithParameterDict:dict successBlock:^(NSMutableArray *photoMatchArray) {
        [GMTipsHelper showDismiss];
        [self.photoMatchColumnView.pullToRefreshView stopAnimating];
        self.pageNum +=1;
        [self.gameListModelArray removeAllObjects];
        self.gameListModelArray=[photoMatchArray mutableCopy];
        if(photoMatchArray.count==0){
        
            self.nodataFlag=YES;
        }
        
        [self.photoMatchColumnView reloadData];
        
    } failBlock:^{
        //
        [GMTipsHelper showDismiss];
        [self.photoMatchColumnView.pullToRefreshView stopAnimating];
    }];
}

-(void)toTrigger{
    
    NSString *lastUpdateTime = [UserDefaults_GetObject(NSStringFromClass([self class])) sinceNowDescription];
    if(!lastUpdateTime.length)
        lastUpdateTime = NSLocalizedString(STR_NeverRefresh, );
    NSString *lastUpdateStr = PCStrFormat(@"%@%@", NSLocalizedString(STR_LastAt, ), lastUpdateTime);
    [self.photoMatchColumnView.pullToRefreshView setSubtitle:lastUpdateStr forState:SVPullToRefreshStateAll];
}

-(void)toLoadMore{
    
    NSDictionary *dict=[self parameterObj];
    
    [[fetchData shared] fetchMatchListWithParameterDict:dict successBlock:^(NSArray *photoMatchArray) {
        
        [self.photoMatchColumnView.infiniteScrollingView stopAnimating];
        
        self.pageNum +=1;
        
        for(NSDictionary *dict in photoMatchArray){
            
            [self.gameListModelArray addObject:dict];
        }
        
        [self.photoMatchColumnView reloadData];
        
    } failBlock:^{
        //
        [self.photoMatchColumnView.infiniteScrollingView stopAnimating];
        
    }];
}

-(void)searchPhotoMatch{
    
    NSDictionary *dictMid=[self parameterObj];
    self.searchPageNum=1;
    
    NSDictionary *dict=@{@"uuid":dictMid[@"uuid"],@"sort_type":dictMid[@"sort_type"],@"search_key":dictMid[@"search_key"],@"page":@1,@"token":dictMid[@"token"]};
    
    [[fetchData shared] fetchMatchListWithParameterDict:dict successBlock:^(NSArray *photoMatchArray) {
        
        [self.photoMatchColumnView.pullToRefreshView stopAnimating];
        self.searchPageNum +=1;
        [self.searchMatchArray removeAllObjects];
        self.searchMatchArray=[photoMatchArray mutableCopy];
        if(photoMatchArray.count==0){
            
            self.nodataFlag=YES;
        }
        
        [self.photoMatchColumnView reloadData];
        
    } failBlock:^{
        //
        [self.photoMatchColumnView.pullToRefreshView stopAnimating];
    }];
}

-(void)searchPhotoMatchLoadMore{
    
    NSDictionary *dictMid=[self parameterObj];
    
    [[fetchData shared] fetchMatchListWithParameterDict:dictMid successBlock:^(NSArray *photoMatchArray) {
        
        [self.photoMatchColumnView.infiniteScrollingView stopAnimating];
        self.searchPageNum +=1;
        
        for(NSDictionary *dict in photoMatchArray){
            
            [self.searchMatchArray addObject:dict];
        }
        
        [self.photoMatchColumnView reloadData];
        
    } failBlock:^{
        //
        [self.photoMatchColumnView.infiniteScrollingView stopAnimating];
        
    }];
}

#pragma mark - property
-(UIButton *)cancelBtn{
    
    if(_cancelBtn==nil){
        
        _cancelBtn=[[UIButton alloc] init];
        
        [_cancelBtn setTintColor:[UIColor colorWithRed:1.0 green:102.0/255.0 blue:102.0/255.0 alpha:1.0]];
        [_cancelBtn setTitleColor:[UIColor colorWithRed:1.0 green:102.0/255.0 blue:102.0/255.0 alpha:1.0] forState:UIControlStateNormal];
        [_cancelBtn addTarget:self action:@selector(cancelBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        _cancelBtn.titleLabel.font=[UIFont systemFontOfSize:15];
        _cancelBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentCenter;
        _cancelBtn.contentEdgeInsets=UIEdgeInsetsMake(0, 0, 7, 0);
    }
    
    return _cancelBtn;
}

-(UIView *)searchAlphaView{
    
    if(_searchAlphaView==nil){
        
        _searchAlphaView=[[UIView alloc] initWithFrame:CGRectMake(0, topNavH, SCREEN_W, SCREEN_H-topNavH)];
        _searchAlphaView.backgroundColor=[UIColor colorWithWhite:0 alpha:0.5];
    }
    
    return _searchAlphaView;
}

-(UIView *)redLineView{
    
    if(_redLineView==nil){
        
        _redLineView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 0.5)];
        _redLineView.backgroundColor=[UIColor colorWithRed:1.0 green:102/255.0 blue:102/255.0 alpha:1.0];
    }
    
    return _redLineView;
}

-(NSMutableArray *)gameListModelArray{
    
    if(_gameListModelArray==nil){
        
        _gameListModelArray=[[NSMutableArray alloc] initWithCapacity:8];
    }
    
    return _gameListModelArray;
}

-(NSMutableArray *)searchMatchArray{
    
    if(_searchMatchArray==nil){
        
        _searchMatchArray=[[NSMutableArray alloc] initWithCapacity:8];
    }
    
    return _searchMatchArray;
}

-(searchBar *)searchBar{
    
    if(_searchBar==nil){
        
        UINib *nib=[UINib nibWithNibName:@"searchBar" bundle:[NSBundle mainBundle]];
        _searchBar=[[nib instantiateWithOwner:nil options:nil] firstObject];
        _searchBar.frame=CGRectMake(SCREEN_W, statusBarH, SCREEN_W, topNavH);
        _searchBar.delegate=self;
        
        for (UIView *view in [[_searchBar.subviews lastObject] subviews]) {
            
            if([view isKindOfClass:NSClassFromString(@"UINavigationButton")]){
                
                UIButton *btn=(UIButton *)view;
                [btn setTitle:nil forState:UIControlStateNormal];
                [btn setTitleColor:[UIColor clearColor] forState:UIControlStateNormal];
            }
            
            if ([view isKindOfClass:NSClassFromString(@"UISearchBarTextField")]) {
                CGColorSpaceRef coloSpRef=CGColorSpaceCreateDeviceRGB();
                CGColorRef colorRef=CGColorCreate(coloSpRef, (CGFloat[]){200/255.0,200/255.0,200/255.0,1});
                UITextField *textField = (UITextField *)view;
                [textField setBackgroundColor:[UIColor whiteColor]];
                textField.layer.cornerRadius=12.50;
                textField.layer.borderWidth=0.5;
                textField.layer.borderColor=colorRef;
            }
        }
    }
    [self.cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    self.cancelBtn.frame=CGRectMake(SCREEN_W-cancelBtnW, 0, cancelBtnW, topViewAndStatusBarH);
    [[_searchBar.subviews lastObject] addSubview:self.cancelBtn];
    
    return _searchBar;
}

-(NSDictionary *)parameterObj{
    
    if(self.pageNum==0){
        
         self.pageNum=1;
    }
   
    NSNumber *pageObj=[NSNumber numberWithInteger:self.pageNum];
    id uuidObj=[self uuidObj];
    sortType *sType=self.sorType;
    id searchKey=[self searchKeyObj];
    id token=[self tokenObj];
    
    NSDictionary *dict=@{@"uuid":uuidObj,@"sort_type":sType,@"search_key":searchKey,@"page":pageObj,@"token":token};
    
    return dict;
}

-(id)uuidObj{
    
    id uuidObj;
    if([NSString isEmptyString:self.UUID]){
        
        uuidObj=[NSNull null];
        
    }else{
        
        uuidObj=self.UUID;
    }
    
    return uuidObj;
}

-(id)searchKeyObj{
    
    id searchKeyObj;
    
    if([NSString isEmptyString:self.searchKeyText]){
        
        searchKeyObj=[NSNull null];
        
    }else{
    
        searchKeyObj=self.searchKeyText;
    }
    
    return searchKeyObj;
}

-(id)tokenObj{
    
    id tokenObj;
    PCUserModel *userModel = [[PCUserInfoManager sharedUserInfo] readUserInfo];
    self.token=userModel.userToken;
    
    if([NSString isEmptyString:self.token]){
        
        tokenObj=[NSNull null];
        
    }else{
        
        tokenObj=self.token;
    }
    
    return tokenObj;
}

-(sortType *)sorType{
    
    if(self.segmentCtrl.selectedSegmentIndex==1){
        
        _sorType=@"vote_count";
    
    }else{
        
        _sorType=@"date";

    }
    
    return _sorType;
}

-(UICollectionView *)photoMatchColumnView{
    
    if(_photoMatchColumnView==nil){
        
        UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
        flowLayout.scrollDirection=UICollectionViewScrollDirectionVertical;
        
        _photoMatchColumnView=[[UICollectionView alloc] initWithFrame:CGRectMake(0, 0.5, SCREEN_W, SCREEN_H-topNavAndStatusBarH+0.5) collectionViewLayout:flowLayout];
        
        UINib *nodataNib=[UINib nibWithNibName:@"nodataCell" bundle:[NSBundle mainBundle]];
        [_photoMatchColumnView registerNib:nodataNib forCellWithReuseIdentifier:nodataCellID];
        
        UINib *leftcellNib=[UINib nibWithNibName:@"leftCell" bundle:[NSBundle mainBundle]];
        [_photoMatchColumnView registerNib:leftcellNib forCellWithReuseIdentifier:leftCellID];
        
        UINib *rightcellNib=[UINib nibWithNibName:@"rightCell" bundle:[NSBundle mainBundle]];
        [_photoMatchColumnView registerNib:rightcellNib forCellWithReuseIdentifier:rightCellID];
        
    }
    
    return _photoMatchColumnView;
}

-(CGRect)photoMatchColumnViewRect{
    
    if(CGRectIsEmpty(_photoMatchColumnViewRect) || CGRectIsNull(_photoMatchColumnViewRect)){
        
        CGFloat x=0;
        CGFloat y=0.5;
        CGFloat h=SCREEN_H-topNavAndStatusBarH;
        _photoMatchColumnViewRect=CGRectMake(x, y, SCREEN_W, h);
    }
    
    return _photoMatchColumnViewRect;
}

#pragma mark - button Action

- (IBAction)segmentCtrlAction:(UISegmentedControl *)sender {
    
    if(sender.selectedSegmentIndex==1){
        //更多作品
        [self toRefresh];
        
    }else{
        //最新作品
        [self toRefresh];
    }
}

- (IBAction)backBtnAction:(UIButton *)sender {
    //
    [GMTipsHelper showDismiss];
    self.searchingFlag=NO;
    [self.navigationController popViewControllerAnimated:YES];

}

- (IBAction)searchBtnAction:(UIButton *)sender {
    
    MCHiddenNavBar();
    self.searchingFlag=YES;
    [self configRefresh];
    [self.view addSubview:self.searchAlphaView];
    [self.view bringSubviewToFront:self.searchAlphaView];
    
    self.redLineView.backgroundColor=[UIColor whiteColor];
    self.photoMatchColumnView.frame=CGRectMake(0, topNavH+0.5, SCREEN_W, SCREEN_H-topNavAndStatusBarH+0.5);
    [self.view addSubview:self.searchBar];
    [self.view bringSubviewToFront:self.searchBar];
    
    [self.searchBar becomeFirstResponder];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.searchBar.frame=CGRectMake(0, statusBarH, SCREEN_W, topNavH);
        self.searchBar.backgroundColor=[UIColor whiteColor];
    }];
}

-(void)cancelBtnAction:(UIButton *)btn{
    
    [self searchBarCancelButtonClicked:self.searchBar];
}

#pragma mark - UICollecitonView Delegate,dataSource,flowlayout delegate
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    NSInteger num=0;
    
    if(self.searchingFlag){
        
        num=(self.searchMatchArray.count==0 && self.nodataFlag==YES ? 1 : self.searchMatchArray.count);
        
    }else{
        
        num=((self.gameListModelArray.count==0 && self.nodataFlag==YES) ? 1 : self.gameListModelArray.count);
    }
    
    return num;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSArray *midArray;
    if(self.searchingFlag){
        
        midArray=self.searchMatchArray;
        
    }else{
        
        midArray=self.gameListModelArray;
        
    }
    
    if(midArray.count==0){
        
        nodataCell *nodataCell=[collectionView dequeueReusableCellWithReuseIdentifier:nodataCellID forIndexPath:indexPath];
        return nodataCell;
        
    }else{
        
        NSString *imageURL=(((gameListModel *)midArray[indexPath.item]).imageURL);
        NSString *title=(((gameListModel *)midArray[indexPath.item]).title);
        NSString *author=(((gameListModel *)midArray[indexPath.item]).author);
        NSInteger vote=(((gameListModel *)midArray[indexPath.item]).votesCount);
        
        if(indexPath.item%2==0){
            //left cell
            leftCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:leftCellID forIndexPath:indexPath];
            [cell configCellWithImageURL:imageURL andTitle:title andAuthor:author andVote:vote];
            
            if(indexPath.item==0){
                
                [cell removeTopBlackLineView];
            }
            
            return cell;
            
        }else{
            //right cell
            rightCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:rightCellID  forIndexPath:indexPath];
            [cell configCellWithImageURL:imageURL andTitle:title andAuthor:author andVote:vote];
            
            if(indexPath.item==1){
                
                [cell removeTopBlackLineView];
            }
            
            return cell;
        }
    }
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    
    return 0.0;
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    
    return 0.0;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSArray *midArray;
    if(self.searchingFlag){
        
        midArray=self.searchMatchArray;
        
    }else{
        
        midArray=self.gameListModelArray;
        
    }
    
    CGSize cellSize=(midArray.count==0 ? CGSizeMake(SCREEN_W, self.photoMatchColumnViewRect.size.height) : CGSizeMake(cellW,cellH));
    
    return cellSize;
}

-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    BOOL seFlag;
    
    if(self.searchingFlag){
        
        seFlag=(self.searchMatchArray.count==0 ? NO : YES);
        
    }else{
        
        seFlag=(self.gameListModelArray.count==0 ? NO : YES);
    }
    
    return seFlag;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    //跳转至大赛图片详情
    UIStoryboard *showVCStory=[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    PCShowPhotoCommVC *showVC=[showVCStory instantiateViewControllerWithIdentifier:@"PCShowPhotoCommVC"];
    [showVC passPhotoMatchUUID:(((gameListModel *)self.gameListModelArray[indexPath.item]).uuid)];
    [showVC passVCType:photoMatchDetailVC];
    
    [self.navigationController pushViewController:showVC animated:YES];
}

#pragma mark - searchBarDelegate
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    //click cancel,dismiss seachBar,show navBar
    [self.searchBar resignFirstResponder];
    self.searchKeyText=nil;
    self.searchingFlag=NO;
    [self configRefresh];
    [UIView animateWithDuration:0.3 animations:^{
        
        [self.searchBar removeFromSuperview];
        [self.searchAlphaView removeFromSuperview];
        MCShowNavBar();
        self.redLineView.backgroundColor=[UIColor colorWithRed:255/255.0 green:102/255.0 blue:102/255.0 alpha:1.0];
        self.photoMatchColumnView.frame=CGRectMake(0, 0.5, SCREEN_W, SCREEN_H-topNavAndStatusBarH+0.5);
        
    }completion:^(BOOL finished) {
        
        [self.photoMatchColumnView reloadData];
    }];
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    //点击键盘search按钮执行搜索
    [self.searchBar resignFirstResponder];
    self.searchingFlag=YES;
    [self.searchAlphaView removeFromSuperview];
    self.searchKeyText=searchBar.text;
    [self searchPhotoMatch];
}

@end
